<template>
  <div class="app-user">
  <Query
     :items="queryColumns"
     :initial-params="queryParams"
     @query="handleQuery"
   />
   <Table
     :table-columns="tableColumns"
     :table-loading="tableLoading"
     :table-data="tableData"
     :total="total"
     :showIndex="true"
     @pagination="handlePagination"
   >
    <template v-slot:tools>
       <el-button-group>
         <el-button type="primary" @click="handleAdd">添加角色</el-button>
       </el-button-group>
     </template>
     <template #opt="scope">
      <el-button type="primary" link @click="setRole(scope.row)">编辑</el-button>
       <el-button type="danger" link @click="changeValue(scope.row)">移除</el-button>
     </template>
   </Table>
  </div>

  <el-dialog v-model="show" title="角色信息" width="500">
    <el-form :model="form">
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="form.roleName" autocomplete="off" />
      </el-form-item>

      <el-form-item label="权限" :label-width="formLabelWidth">
        <el-tree
          ref="treeRef"
          :data="permList"
          show-checkbox
          node-key="id"
          :props="{
            children: 'itemList',
            label: 'name'
          }"
          @check="handleCheck"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="role">
import Table from "@/components/Table/index.vue";
import Query from "@/components/Query/index.vue";
import { getSysRoleList, saveRoles, getRolePermission } from "@/api/system/role";
import { ref, reactive, toRefs, nextTick } from "vue";
import { allPagesRoutes } from "@/router";
const { proxy } = getCurrentInstance()
const tableData = ref([])
const total = ref(0)
const tableLoading = ref(true)
const loading = ref(false)
const showDialog = ref(false)
const router = useRouter();

const show = ref(false)
const data = reactive({
 tableColumns: [
   { label: "角色名", prop: "roleName", },
   { label: "员工账号数", prop: "staffNum" },
   { label: "创建时间", prop: "gmtCreate"},
   { label: "操作",  prop: "opt", slot: 'opt'},
 ],
 queryColumns: [
 ],
 pageParams: {
  current: 1,
  size: 10
 },
 queryParams: {},
 formItems: []
})

const permList = ref([])
const getpermList = (roleId) =>{
  if(roleId){
    return getRolePermission(roleId).then(res => {
      console.log(11,res.data.checkedKeys)
      if(res.code == 200){
        return res.data.checkedKeys;
      }
      return [];
    })
  } else {
    // 使用本地配置的 allPagesRoutes 数据，并过滤掉 hidden:false 的路由
    const filterHiddenRoutes = (routes) => {
      return routes.filter(route => {
        // 过滤掉 hidden:false 的路由
        if (route.hidden === true) {
          return false;
        }
        
        // 处理子路由
        if (route.children && route.children.length) {
          route.itemList = filterHiddenRoutes(route.children);
        } else {
          route.itemList = [];
        }
        
        // 转换属性名以匹配树组件需要的格式
        route.name = route.meta?.title || route.name;
        
        return true;
      });
    };
    
    // 深拷贝 allPagesRoutes 并过滤
    const clonedRoutes = JSON.parse(JSON.stringify(allPagesRoutes));
    permList.value = filterHiddenRoutes(clonedRoutes);
    return Promise.resolve([]);
  }
}
getpermList();

const form = ref({
  id:'',
  roleName: '',
  permIdList: []
})

const { tableColumns, queryColumns, pageParams, queryParams } = toRefs(data)
/** 获取列表数据 */
const getList = () => {
  tableLoading.value = true
  const data  = {
     ...queryParams.value,
     ...pageParams.value
  }
  getSysRoleList(data)
   .then(res => {
       tableData.value = res.data.records
       total.value = res.data.totalRow
   })
   .finally(() => {
       tableLoading.value = false
   })
}
getList()

/** 搜索按钮操作 */
const handleQuery = (val) => {
 queryParams.value = val
 getList()
}

const handlePagination = (val) => {
 pageParams.value = val
 getList()
}
/* 创建 */
const handleAdd = () => {
  form.value = {
    id: '',
    roleName: '',
    permIdList: []
  };
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([]); // 清空所有选中
  }
  getpermList(); // 重新加载所有权限树
  show.value = true
}
const save = () => {
  if (!form.value.roleName) {
    proxy.$modal.msgError('角色名称不能为空')
    return
  }
  
  saveRoles(form.value).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess('保存成功')
      show.value = false
      getList()
      getpermList();
    } else {
      proxy.$modal.msgError(res.msg || '保存失败')
    }
  })
  .catch(() => {
    proxy.$modal.msgError('保存失败')
  })
}

const changeValue = (row) => {
 proxy.$modal.confirm(`是否确认移除此角色？`)
 .then(() => {
   saveRoles({ id: row.id, delFlag: -1}).then(() => {
     proxy.$modal.msgSuccess("操作成功")
     getList()
   })
 })
}

const treeRef = ref()

const handleCheck = (data, checked) => {
  form.value.permIdList = checked.checkedKeys
}

const setRole = (row) => {
  form.value.id = row.id;
  form.value.roleName = row.roleName;

  getRolePermission(row.id).then(res => {
    console.log(res.data)
    show.value = true;
    nextTick(() => {
      const checkedKeys = ref([])
      let arr = []
      res.data.forEach(item=>{
        arr.push(item.id)
        if(item.itemList){
          item.itemList.forEach(item2=>{
            arr.push(item2.id)
          })
        }
      })
      checkedKeys.value = arr
      console.log(11,treeRef.value)
      if (treeRef.value) {
        treeRef.value?.setCheckedKeys(checkedKeys.value,true);
        form.value.permIdList = checkedKeys.value;
      }
    });
  })
};
</script>
<style lang="scss">
.app-user {
 padding: 8px;
}
</style>